package com.lu.business.core.response;

import lombok.Getter;
import lombok.experimental.Accessors;

import java.util.HashMap;
import java.util.Map;

/**
 * @program web-admin
 * @description: 系统响应
 * @author: zhanglu
 * @create: 2020-10-21 19:46:00
 */
@Getter
@Accessors(chain = true)
public class ResponseResult<T> {

    private Integer code;
    private String msg;
    private T data;
    private long timestamp;
    private Map<String, Object> params = null;

    public static <T> ResponseResult<T> success(){
        return result(null, 1, "操作成功");
    }

    public static <T> ResponseResult<T> success(T data){
        return result(data, 1, "操作成功");
    }

    public static <T> ResponseResult<T> failed(){
        return result(null, 0, "操作失败");
    }

    private static <T> ResponseResult<T> result(T data, Integer code, String msg) {
        ResponseResult<T> result = new ResponseResult<>();
        result.code(code);
        result.data(data);
        result.msg(msg);
        result.timestamp(System.currentTimeMillis());
        return result;
    }

    public ResponseResult<T> code(Integer code) {
        this.code = code;
        return this;
    }

    public ResponseResult<T> msg(String msg) {
        this.msg = msg;
        return this;
    }

    public ResponseResult<T> data(T data) {
        this.data = data;
        return this;
    }

    public ResponseResult<T> timestamp(Long timestamp) {
        this.timestamp = timestamp;
        return this;
    }

    public ResponseResult<T> params(String k, Object v){
        if(this.params == null){
            this.params = new HashMap<>();
        }
        this.params.put(k, v);
        return this;
    }

    public boolean isFailed(){
        return this.code == null || this.code < 0;
    }

    public boolean isSuccess(){
        return this.code != null && this.code >= 0;
    }

}
